
var jfinal = new JFINAL();

function JFINAL() {
	/**
	 * 一次修改一条记录的时候使用该方法
	 */
	this.insertRecord = _insertRecord;
	/**
	 * 一次修改一条记录的时候使用该方法
	 */
	this.updateRecord = _updateRecord;
	/**
	 * 重置表单，刷新表格
	 */
	this.queryReset = _queryReset;
	/**
	 * 查询数据
	 */
	this.queryRecord = _queryRecord;
	/**
	 * 一次删除一条或者多条记录的时候使用该方法
	 */
 	this.deleteRecord = _deleteRecord;
 	/**
 	 * 一次清空所有数据
 	 */
 	this.deleteAll = _deleteAll;
 	/**
 	 * 弹出提示对话框
 	 */
 	this.easyAlert = _easyAlert;
 	/**
 	 * 获取选中单行记录指定列的值(单选带弹出提示)
 	 */
 	this.singleSelect = _singleSelect;
 	/**
 	 * 获取选中单行记录指定列的值
 	 */
 	this.getSelection = _getSelection;
 	/**
 	 * 获取选中多行记录指定列的值
 	 */
 	this.getSelections = _getSelections;
 	/**
 	 * 添加自定义分页条
 	 */
 	this.addPagerToolBar = _addPagerToolBar;
 	/**
 	 * 添加自定义分页条
 	 */
 	this.addPagerToolBarCombo = _addPagerToolBarCombo;
 	/**
 	 * 异步提交
 	 */
 	this.ajaxPost = _ajaxPost;

 	/**
 	 * 打开一个弹出框
 	 */
 	this.openDialog = _openDialog;
 	
 	this.showProcess = _showProcess;
 	
 	this.closeProgress = _closeProgress;
 	
 	this.exportExcel = _exportExcel;
 	
 	this.closeCurrentTab = _closeCurrentTab;
 	
 	this.closeTab = _closeTab;
 	
 	this.onUpdateTab = _onUpdateTab;
 	
 	this.onAddTab = _onAddTab;
 	
 	/**
 	 * 左下角弹出信息
 	 */
 	this.message = _message;
 	
 	this.onSave = _onSave;
 	this.onClose = _onClose;
 	this.onDelete = _onDelete;
 	this.onQuery = _onQuery;
 	this.onReset = _onReset;
 	this.onAdd = _onAdd;
 	this.onUpdate = _onUpdate;
 	this.datagrid = _datagrid;
 	this.combogrid = _combogrid;
 	this.treegrid = _treegrid;
 	this.form = _form;
 	
	function _onSave(form){
 		$('#'+form).submit();   
 	}
	
	function _onClose(dlg){
		$('#'+dlg).dialog("close");
	}
	
	function _onDelete(dg,action){
		_deleteRecord($('#'+dg),action+'.jhtml', "id");
	}
	
	function _onQuery(form,dg){
		_queryRecord($('#'+form), $('#'+dg));
	}
	
	function _onReset(form,dg){
		_queryReset($('#'+form), $('#'+dg));
	}
	
	function _onAdd(dg,dlg,action,title,w,h){
		_openDialog($('#'+dlg), action+'/'+dg+'-'+dlg+'.jhtml', title, w, h);
	}
	
	function _onUpdate(dg,dlg,action,title,w,h){
		var id = _singleSelect($('#'+dg), "id");
		if(id){
			_openDialog($('#'+dlg), action+'/'+dg+'-'+dlg+"-"+id+".jhtml", title, w, h);
		}
	}
	
	function _datagrid(dg,action,tb,frozenColumns,columns){
		var datagrid = $('#'+dg).datagrid({
			url:action+'.jhtml',
			fit:true,
			rownumbers:true,
			pagination:true,
			toolbar:'#'+tb,
			remoteSort: false,
			pageSize:20,
			method:'post',
			onLoadError:function(){
	    		alert("加载错误！请刷新页面或者重新登录！");
	    	},
	    	onLoadSuccess:function(){
	    		$('#'+dg).datagrid('unselectAll');
	    	},
			frozenColumns :frozenColumns,
			columns:columns
		});
		return datagrid;
	}
	
	function _combogrid(cg,action,columns,idField,textField){
		var combogrid = $('#'+cg).combogrid({    
		    panelWidth:450,    
		    idField:idField,    
		    textField:textField,   
		    pageSize:20,
		    pagination:true,
		    remoteSort: false,
		    editable:false,
		    url:action+'.jhtml',
		    onSelect:function(rowIndex, rowData){
		    	$('#'+cg).val(rowData.id)
		    },
		    columns:columns
		});  
		return combogrid;
	}
	
	function _treegrid(tg,action,tb,treeField,columns){
		var treegrid = $('#'+tg).treegrid({
			url:action+'.jhtml',
			fit:true,
			rownumbers:true,
			pagination:true,
			toolbar:'#'+tb,
			remoteSort: false,
			pageSize:20,
			method:'post',
			idField: 'id',
            treeField: treeField,
			onLoadError:function(){
				alert("加载错误！请刷新页面或者重新登录！");
			},
			onBeforeLoad: function(row,param){
                /*if (!row) {
                    param.id = 0;
                }*/
            },
			columns:columns
		});
		return treegrid;
	}
 	
	function _form(form,action,dg,dialog,spanMsg){
		 var former = $("#"+form).form({
					url : action+'.jhtml',
					dataType : "text",
					success : function(data) {
						 var result = $.parseJSON(data);
						 if(result.isSuccess == true){
							 if(result.closeCurrentTab)
								 _closeCurrentTab();
							 else
								 _onClose(dialog);
							 _message(result.msg);
							 $("#"+dg).datagrid('reload');
						 }else{
							 $("#"+spanMsg).html(result.msg);
							 return;
						 }
					},
					onLoadError : function(data) {
					}
				});
		 return former;
	 }
	
 	/**
 	 * 左下角弹出信息
 	 */
 	function _message(info){
 		$.messager.show({
 			title:'提示信息',
 			msg:"<b>"+info,
 			timeout:2000,
 			showType:'slide'
 		});
 		return;
 	}

 	/**
 	 * 新增一条记录
 	 */
 	function _insertRecord($form,action){
 		$form.attr("action",action);
 		$form.submit();   
 	}

 	/**
 	 * 更新一条记录
 	 */
 	function _updateRecord($form,action,$datagrid,id){
 		$form.attr("action", action+"?ids="+_singleSelect($datagrid,id));
 		$form.submit();   
 	}

 	/**
 	 * 获取选中单行记录指定列的值(单选带弹出提示)
 	 */
 	function _singleSelect($datagrid,id){
 		if(_getSelections($datagrid,id).length < 1) {
 			_easyAlert("必须选择一行！");
 			return;
 		} else if (_getSelections($datagrid,id).length > 1) {
 			_easyAlert("只能选择一行, 不允许多选！");
 			return;
 		}  
 		return _getSelection($datagrid,id);
 	}

 	/**
 	 * 获取选中单行记录指定列的值
 	 */
 	function _getSelection($datagrid,id) {
 		var row = $datagrid.datagrid('getSelections');
 		if (row)
 			return row[0][id];
 		else
 			return null;
 	}

 	/**
 	 * 获取选中多行记录指定列的值
 	 */
 	function _getSelections($datagrid, id) {
 		var ids = [];
 		var rows = $datagrid.datagrid('getSelections');
 		for ( var i = 0; i < rows.length; i++) {
 			var row = rows[i];
 			ids[i] = row[id];
 		}
 		return ids;
 	}

 	/**
 	 *查询数据
 	 */
 	var isLoad = false;//设置标志表明当前查询加载是否完成，如果没有完成不进行下一次查询
 	function _queryRecord( $form,$datagrid) {
 		var data = $form.serializeJson();
 		if (!isLoad) {
 			isLoad = true;
 			$datagrid.datagrid("load",data);
 			isLoad=false;
 		}
 	}

 	/**
 	 * 重置查询表单，刷新表格
 	 */
 	function _queryReset( $form,$datagrid) {
 		$form.form("reset");
 		_queryRecord($form,$datagrid);
 	}

 	/**
 	 * 弹出提示对话框
 	 */
 	function _easyAlert(msg){
 		$.messager.alert("提示",msg,"info");
 	}

 	/**
 	 * 一次清空所有数据
 	 */
 	function _deleteAll($datagrid,action){
 		$.messager.confirm('确认','您确认想要清空所有记录吗？',function(r){    
 		    if (r){    
 		    	$.post(action, null,function(result){
 		    		$.messager.show({
 		    			title:'提示信息',
 		    			msg:"<b>清空成功！",
 		    			timeout:2000,
 		    			showType:'slide'
 		    		});
 			 		$datagrid.datagrid('reload');
 			    });
 		    }    
 		});  
 		return;
 	}

 	/**
 	 * 一次删除一条或者多条记录的时候使用该方法
 	 */
 	function _deleteRecord($datagrid, action, id) {
 		var ids = _getSelections($datagrid,id);
 		if(ids.length < 1) {
 			_easyAlert("必须选择一行！");
 			return;
 		} else if (ids.length >= 1) {
 			var param = {};
 			$.each(ids, function(i,n) {
 				if (param["ids"]) {
 					param["ids"] += "," + n;
 				} else {
 					param["ids"] = n || '';
 				} 
 			});
 			$.messager.confirm('确认','您确认想要删除记录吗？',function(r){    
 			    if (r){    
 			    	$.post(action, param,function(result){
 			    		$.messager.show({
 			    			title:'提示信息',
 			    			msg:"<b>删除成功！共删除记录"+ids.length+"条",
 			    			timeout:2000,
 			    			showType:'slide'
 			    		});
 				 		$datagrid.datagrid('reload');
 				    });
 			    }    
 			});  
 			return;
 		} 
 	}

 	/**
 	 * 直接打开一个dialog框，新增功能等使用
 	 */
 	function _openDialog($dialog,action,title,width,height){
 		$dialog.dialog({
 		    title: title,
 		    width: width,
 		    height: height,
 		    closed: false,
 		    cache: false,
 		    href: action,
 		    modal: true
 		});
 	}

 	/**
 	 * 异步提交
 	 */
 	function _ajaxPost(url,data,callback){
 		$.ajax({
 			type : "post",
 			url : url+'.jhtml',
 			data : data,
 			error:function(data){
 				_closeProgress();
 				_easyAlert("Ajax调用出错！");
 			},
 			success :callback
 		});
 	}

 	/**
 	 * 添加自定义分页条
 	 */
 	function _addPagerToolBar($datagrid){
 		//设置分页控件 
 		var p = $datagrid.datagrid('getPager'); 
 		p.pagination({ 
 		    pageList: [20,40,60],//可以设置每页记录条数的列表 
 		    beforePageText: '第',//页数文本框前显示的汉字 
 		    afterPageText: '页    共 {pages} 页', 
 		    displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录', 
 		});  
 	}

 	/**
 	 * 添加自定义分页条
 	 */
 	function _addPagerToolBarCombo($combogrid){
 		//设置分页控件 
 		var p = $combogrid.combogrid('grid').datagrid('getPager'); 
 		p.pagination({ 
 		    pageList: [20,40,60],//可以设置每页记录条数的列表 
 		    beforePageText: '第',//页数文本框前显示的汉字 
 		    afterPageText: '页    共 {pages} 页', 
 		    displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录', 
 		});  
 	}
 	
 	/**
 	 * 显示进度条
 	 */
 	function _showProcess(msg) {
 		$.messager.progress({
 			 title: "提示",
 			 msg: msg
 		});
 	 }
 	
 	/**
 	 * 关闭进度条
 	 */
 	function _closeProgress(){
 		$.messager.progress('close');
 	}
 	
 	/**
 	 * 导出excel所有数据的操作
 	 */
 	function _exportExcel(action){
 		$.messager.confirm("确认","确认导出excel吗?",function(r){
 			 if (r){
 				 window.location = action;
 			 }else{
 					return;
 			 }
 		});
 	}
 	
 	/**
 	 * 关闭当前显示的tab
 	 */
 	function _closeCurrentTab(){
 		var tab = $("#tabs").tabs("getSelected");
 		var index = $("#tabs").tabs("getTabIndex",tab);
 		$("#tabs").tabs("close", index);
 	}
 	
 	/**
 	 * 关闭指定标题的tab
 	 */
 	function _closeTab(title){
 		$("#tabs").tabs("close", title);
 	}
 	
 	/**
 	 * 打开一个tab
 	 */
 	function _openTab(action,title){
 		if ($("#tabs").tabs("exists", title)){
 			_closeTab(title);
 	    }
 		$("#tabs").tabs("add",{
 			title:title,   
 			href:action,   
 			closable:true
 		});
 	}
 	
 	/**
 	 * 打开一个tab，修改
 	 */
 	function _onUpdateTab(dg,action,title){
 		var id = _singleSelect($('#'+dg), "id");
		if(id){
			_openTab(action+"/"+dg+"-"+id+".jhtml",title);
		}
 	}
 	
 	/**
 	 * 打开一个tab，新增
 	 */
 	function _onAddTab(dg,action,title){
		_openTab(action+"/"+dg+".jhtml",title);
 	}
 	
}

/**
 * 格式化表单参数
 */
$.fn.serializeJson = function() {
    var serializeObj = {};
    var array = this.serializeArray();
    $(array).each(
            function() {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [
                                serializeObj[this.name], this.value ];
                    }
                } else {
                    serializeObj[this.name] = this.value;
                }
            });
    return serializeObj;
};